

library(tidyverse)
library(rio)
library(countrycode)
library(wesanderson)

setwd("~/05_vreeland_2008")

full_data <- import("replication_data.dta") %>%
  filter(year>1984 & year<1997 & reg==1 & wdiname!="") 


world <- map_data("world") %>%
  filter(region != "Antarctica") %>%
  mutate(wdicode = countrycode(region, 'country.name', 'wb', warn = T))


data_og <- full_data %>%
  select(wdicode,year,reg,torture,party,level,g,population,tradegdp,war,communist)%>%
  drop_na() %>%
  group_by(wdicode) %>%
  tally() %>%
  unique() %>%
  right_join(world) %>%
  cbind(name = "Original Data")

data_1998 <- full_data %>%
  select(wdicode,year,reg,torture,party,level_1998,g,population,tradegdp,war,communist)%>%
  drop_na() %>%
  group_by(wdicode) %>%
  tally() %>%
  unique() %>%
  right_join(world) %>%
  cbind(name = "WDI 1998")

data_2004 <- full_data %>%
  select(wdicode,year,reg,torture,party,level_2004,g,population,tradegdp,war,communist)%>%
  drop_na() %>%
  group_by(wdicode) %>%
  tally() %>%
  unique() %>%
  right_join(world) %>%
  cbind(name = "WDI 2004")

data_2008 <- full_data %>%
  select(wdicode,year,reg,torture,party,level_2008,g,population,tradegdp,war,communist)%>%
  drop_na() %>%
  group_by(wdicode) %>%
  tally() %>%
  unique() %>%
  right_join(world) %>%
  cbind(name = "WDI 2008")

data_2018 <- full_data %>%
  select(wdicode,year,reg,torture,party,level_2018,g,population,tradegdp,war,communist)%>%
  drop_na() %>%
  group_by(wdicode) %>%
  tally() %>%
  unique() %>%
  right_join(world) %>%
  cbind(name = "WDI 2018")


map_data <- rbind(data_og,data_1998,data_2004,data_2018)

pal <- wes_palette("Zissou1", 100, type = "continuous")
map_data %>%
  ggplot(aes(long, lat, group = group)) + 
  geom_polygon(aes(fill = n), color = "gray92", linewidth = 0.001) + facet_wrap (~ name) + 
  theme_void() + labs(fill="Number of \nAvailable \nObservations") +
  scale_fill_gradientn(colours = pal, na.value="gray92") + 
  theme(plot.margin = unit(c(0,0,0,0), "cm")) +
  theme(strip.text.x = element_text(size = 12, face = "bold", hjust = 0.5))

# ggsave(filename = "map_available_vreeland.pdf", height = 7, width = 12)
